package com.study.manage.interceptor;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.study.manage.dto.AjaxResponse;
import com.study.manage.utils.JsonMapper;



public class TeachInterceptor implements HandlerInterceptor {

    private JsonMapper jsonMapper = new JsonMapper();

    @SuppressWarnings("rawtypes")
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
            Object handler) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        // 验证用户是否登陆
        Map obj = (Map) request.getSession().getAttribute("user");
        if (obj == null || !obj.containsKey("number")) {
            if (handlerMethod.getMethod().getReturnType() == AjaxResponse.class) {
                AjaxResponse ajaxResponse = new AjaxResponse(false);
                ajaxResponse.setMsg("登陆超时或还未登陆，请刷新页面");
                response.getWriter().print(jsonMapper.toJson(ajaxResponse));
            } else {
                String strBackUrl = "http://" + request.getServerName() // 服务器地址
                        + ":" + request.getServerPort() // 端口号
                        + request.getContextPath() // 项目名称
                        + request.getServletPath() // 请求页面或其他地址
                        + "?" + (request.getQueryString() == null ? "" : request.getQueryString()); // 参数
                response.sendRedirect(request.getContextPath() + "/login");
            }
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {}

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
            Object handler, Exception ex) throws Exception {

    }

}
